<%@page import="java.awt.print.Printable"%>
<%@page import="java.lang.reflect.Array"%>
<%@page import="java.util.*"%>
<%@page import="QRCG.DatabaseManager"%>

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Create New Game</title>
<link href="index.css" rel="stylesheet" type="text/css" />
<script src="datetimepicker_css.js"></script>
<script type="text/javascript"
	src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBOaAh2Iu9iwLfxzy9Poj3DSoa6nC4dK3I&sensor=false&region=TR">
	
</script>
<script type="text/javascript">
	// A constant that points to a center of Istanbul.
	var ISTANBUL_LATLNG = new google.maps.LatLng(41.01721057822843,
			28.9764404296875);
	// HintID:Marker map.
	var markerMap = {};
	var map; // The map object.
	// Used for reverse geocoding(getting human readble address from latitude and longitude).
	var geocoder;

	// Images for pin.
	var unselectedImage; // When a hint is not chosen (i.e. its radio button is unchecked)
	var selectedImage; // When a hint is chosen (i.e. its radio button is checked)
	var shadowImage; // Shadow image of the pin.

	var curSelectedHintId; // Keeps the ID of the currently selected hint. Initially, it is undefined.

	var hintBoxCounter = 0; // How many hints there are.
	// How many hints have been created, including the removed ones.
	// Required for unique hint ID (for javascript) generation.
	var idCounter = 0;
	// Prefix of the unique hint ID. An integer is appended to this for the whole ID.
	var HINT_BOX_ID_PREFIX = 'qr_hint';

	var MAX_HINT_NUMBER = 5; // Maximum number of hints.

  // Classes & IDs of some HTML elements.
  var HINT_BOX_CLASS = 'qr_hint_insertion_box';
  var ROOT_HINT_BOX_DIV_ID = 'hints_div';
  var HINT_BOX_RADIO_BUTTON_CLASS = 'qr_hint_radio';
  var HINT_DESCRIPTION_CLASS = 'qr_hint_text_area';
  var HINT_KEYWORD_CLASS = 'qr_hint_keyword';
  var HINT_BOX_COORDINATES_LABEL_CLASS = 'qr_hint_coordinates';
  var HINT_BOX_ADDRESS_LABEL_CLASS = 'qr_hint_address';
  var HINT_REMOVE_BUTTON = 'qr_hint_remove';
  var MAP_CANVAS_ID = 'map_canvas';

	function initialize() {
		var myOptions = {
			zoom : 8, // Zoom level. Greater number means closer.
			center : ISTANBUL_LATLNG, // Initial central position of the map.
			mapTypeId : google.maps.MapTypeId.ROADMAP
		// Type of the map.
		};
		map = new google.maps.Map(document.getElementById(MAP_CANVAS_ID),
				myOptions);
		geocoder = new google.maps.Geocoder();

		// For reference:
		// http://stackoverflow.com/questions/7095574/google-maps-api-3-custom-marker-color-for-default-dot-marker/7686977#7686977
		// http://code.google.com/apis/maps/documentation/javascript/reference.html#MarkerImage
		selectedImage = new google.maps.MarkerImage("images/chosen.png",
				new google.maps.Size(21, 34), // The marker size.
				new google.maps.Point(0, 0), // Origin.
				new google.maps.Point(10, 34)); // Anchor?
		unSelectedImage = new google.maps.MarkerImage("images/normal.png",
				new google.maps.Size(21, 34), new google.maps.Point(0, 0),
				new google.maps.Point(10, 34));
		shadowImage = new google.maps.MarkerImage("images/shadow.png",
				new google.maps.Size(40, 37), new google.maps.Point(0, 0),
				new google.maps.Point(12, 35));

    // Listen to click event on the map.
    google.maps.event.addListener(map, 'click', function(event) {
      addMarker(event.latLng);
    });
    
    addExistingHints();
  }

  /**
   * Adds a marker at a given location for the current selected hint.
   */
  function addMarker(location, getLocationText) {
	  // Default value for getLocationText is true.
	  getLocationText = typeof getLocationText != 'undefined' ? getLocationText : true;
    if (curSelectedHintId) {
      // If a marker has been placed for this hint, remove that.
      if (markerMap[curSelectedHintId]) {
        markerMap[curSelectedHintId].setMap(null);
      }
      // Create the new marker.
      var marker = new google.maps.Marker({
        position : location,
        map : map,
        title : curSelectedHintId, // TODO(cimamoglu): Remove this when this module is complete.
        icon : selectedImage,
        shadow : shadowImage
      });
      // Assign the new marker.
      markerMap[curSelectedHintId] = marker;
      // Update address and longitude/lattitude in HTML.
      if (getLocationText) {
    	  updateLocationText(curSelectedHintId, location);
      }
    }
  }

  function addEmptyHintBox(parentDivId) {
    if (hintBoxCounter < MAX_HINT_NUMBER) {
      var newDiv = document.createElement('div');
      newDiv.id = HINT_BOX_ID_PREFIX + idCounter; // Give a unique ID to the div.
      newDiv.className = HINT_BOX_CLASS;
      // TODO(cimamoglu): This is a very brittle and somewhat ugly solution.
      // This big HTML code chunk must be handled somewhere else with more flexibility.
      // Any change to this current code piece must be done with care.
      // Be careful about quote escaping!
      // You can decompress this expression using http://www.digitalcoding.com/tools/html-beautifier.html
      // To compress again: open Notepad++, replace(choose extended search mode) \r\n with empty string. In regular expression search mode, replace \s\s+ with empty string.
      newDiv.innerHTML = '<div class="' + HINT_BOX_CLASS + '"><table><tr><td><input class="'
          + HINT_BOX_RADIO_BUTTON_CLASS
          + '" type="radio" name="hints" onchange="updateMap(\''
          + newDiv.id
          + '\')">Select Hint</td></tr><tr><td><input name="hint_keywords" class="' + HINT_KEYWORD_CLASS + '" placeholder="Keyword"></td></tr><tr><td><textarea name="hint_descriptions" class="' + HINT_DESCRIPTION_CLASS + '" placeholder="Description"></textarea></td></tr><tr><td><input type="text" class="' + HINT_BOX_COORDINATES_LABEL_CLASS + '" name="hint_coordinates" placeholder="Coordinates" readonly="readonly"></td></tr><tr><td><input type="text" class="' + HINT_BOX_ADDRESS_LABEL_CLASS + '" name="hint_addresses" placeholder="Address" readonly="readonly"></td></tr><tr><td><input type="button" class="'
          + HINT_REMOVE_BUTTON
          + '" onClick="removeHintBox(\''
          + newDiv.id
          + '\')" value="Remove Hint"></td></tr></table></div>';
      document.getElementById(parentDivId).appendChild(newDiv);
      
      // Focus on the new hint box
      var radioButtonEl = newDiv.getElementsByClassName(HINT_BOX_RADIO_BUTTON_CLASS)[0];
      radioButtonEl.click();
      radioButtonEl.checked = true;
      
      ++hintBoxCounter;
      ++idCounter; // This is never decremented!
      return newDiv.id;
    }
  }
  
  function addHint(parentDivId, description, keyword, coordinates, address) {
	  var newHintBoxId = addEmptyHintBox(parentDivId);
	  var hintBoxEl = document.getElementById(newHintBoxId);
	  var keywordEl = hintBoxEl.getElementsByClassName(HINT_KEYWORD_CLASS)[0];
	  var descriptionEl = hintBoxEl.getElementsByClassName(HINT_DESCRIPTION_CLASS)[0];
	  var addressEl = hintBoxEl.getElementsByClassName(HINT_BOX_ADDRESS_LABEL_CLASS)[0];
	  var coordinatesEl = hintBoxEl.getElementsByClassName(HINT_BOX_COORDINATES_LABEL_CLASS)[0];
	  keywordEl.value = keyword;
	  descriptionEl.value = description;
	  coordinatesEl.value = coordinates;
	  addMarker(getLatLngFromString(coordinates), false);
	  addressEl.value = address;
  }
  
  function getLatLngFromString(coordinates) {
	  var nums = coordinates.substr(1, coordinates.length - 2).split(', ');
	  return new google.maps.LatLng(nums[0], nums[1]);
  }

	function updateMarkers(newHintId) {
		// First, set the unselected image. This ordering is important for the
		// border case where user clicks an already checked radio button.
		if (curSelectedHintId && markerMap[curSelectedHintId]) {
			markerMap[curSelectedHintId].setIcon(unselectedImage);
		}
		// Make the new hint chosen.
		if (markerMap[newHintId]) {
			markerMap[newHintId].setIcon(selectedImage);
		}
		// Update the current seleced hint ID variable.
		curSelectedHintId = newHintId;
	}

	function updateMap(hintId) {
		updateMarkers(hintId);
	}
  
  function addExistingHints() {
	  <%
	  String[] hintDescriptions = (String[]) request.getAttribute("hint_descriptions");
	  String[] hintKeywords = (String[]) request.getAttribute("hint_keywords");
	  String[] hintCoordinates = (String[]) request.getAttribute("hint_coordinates");
	  String[] hintAddresses = (String[]) request.getAttribute("hint_addresses");
	  int numHints = hintDescriptions != null ? hintDescriptions.length : 0;
	  
	  for (int i = 0; i < numHints; ++i) {
	  %>
	    addHint('hints_div', '<%= hintDescriptions[i]%>', '<%= hintKeywords[i]%>', '<%= hintCoordinates[i]%>', '<%= hintAddresses[i]%>');
	  <%
	  }
	  %>
  }

	/**
	 * Removes a hint and its associated marker from the map.
	 */
	function removeHintBox(hintId) {
		var child = document.getElementById(hintId);
		var parent = document.getElementById(ROOT_HINT_BOX_DIV_ID);
		parent.removeChild(child);
		--hintBoxCounter;
		markerMap[hintId].setMap(null);
		delete markerMap[hintId];
	}

	/**
	 * Updates the address and longitude/latitude of a hint box.
	 */
	function updateLocationText(hintId, location) {
		coordinatesLabel = document.getElementById(hintId)
				.getElementsByClassName(HINT_BOX_COORDINATES_LABEL_CLASS)[0];
		coordinatesLabel.value = location.toString();

		addressLabel = document.getElementById(hintId).getElementsByClassName(
				HINT_BOX_ADDRESS_LABEL_CLASS)[0];
		// Reference: http://code.google.com/apis/maps/documentation/javascript/services.html#ReverseGeocoding
		geocoder.geocode({
			'latLng' : location
		}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK && results[0]) { // 0th element is the most spesific address.
				addressLabel.value = results[0].formatted_address;
			}
		});
	}
</script>
</head>

<%
	final int MAX_GAMENAME_LENGTH = 30;
	final int MAX_GAMEDESC_LENGTH = 500;
%>

<%@ include file="header.jsp"%>

<%
	if (session.getAttribute("nickname") != null) {
%>

<body onload="initialize()">


<% 	if (request.getAttribute("errorMessages") == null){  %>
	<div class="information-text">
		<table align="center">
			<tr>
				<td>You are about to create a new game!</td>

			</tr>
		</table>
	</div>
<%	} else {
		String[] errors = request.getAttribute("errorMessages").toString().split("\n");
		for(int i=0;i<errors.length;i++){
			%>	<div class="error-message"><%=errors[i]%> </div><%
		}
	}	%>
	<form name="NewGame" method="post" action="CreateGameServe">
		<div id="map_canvas"></div>
		<div id="insert-div">
			<input id="insert-button" type="button"
				onClick="addEmptyHintBox('hints_div')" value="Insert Hint">
		</div>
		<div id="hints_div"></div>

		<div id="post-form">
			<%
				String name = (String) session.getAttribute("nickname");
					session.setAttribute("nickname", name);

					int level_max = 5;
			%>
			<div>
				<table class="post-table">
					<tr>
						<td class="post-label"><b>Name:</b></td>
						<td><input class="post-textbox" type="text"
							maxlength=<%=MAX_GAMENAME_LENGTH %> name="game_name"
							value="${game_name}" /></td>
					</tr>

					<tr>
						<td class="post-label"><b>Description:</b></td>
						<td><input class="post-textbox" type="text"
							maxlength=<%=MAX_GAMEDESC_LENGTH %> name="game_description"
							value="${game_description}" /></td>
					</tr>

					<tr>
						<td class="post-label"><b>Start Date:</b></td>
						<td><input class="post-date" type="text" name="begin_date"
							id="f2" maxlength="10" value="${begin_date}" /> <img
							src="images/cal.gif" alt=""
							onclick="javascript:NewCssCal('f2','yyyyMMdd')"
							class="post-date-image" /></td>
					</tr>

					<tr>
						<td class="post-label"><b>End Date:</b></td>
						<td><input class="post-date" type="text" name="end_date"
							id="f3" maxlength="10" value="${end_date}" /> <img
							src="images/cal.gif" alt=""
							onclick="javascript:NewCssCal('f3','yyyyMMdd')"
							class="post-date-image" /></td>
					</tr>

					<%
						DatabaseManager conn = new DatabaseManager();
							conn.connect();
							ArrayList<HashMap<String, Object>> LocList = conn
									.getAllLocations();
							int numberOfLocations = LocList.size();
					%>
					<tr>
						<td class="post-label"><b>Location</b></td>
						<td><SELECT class="post-selection" name="game_location">
								<%
									int originalLocationId = -1;
										if (request.getAttribute("game_location_id") != null) {
											originalLocationId = Integer.parseInt((String) request
													.getAttribute("game_location_id"));
										}
										for (int i = 0; i < numberOfLocations; i++) {
											HashMap<String, Object> map = (HashMap<String, Object>) LocList
													.get(i);
											int locationId = ((Integer) map.get("location_id"))
													.intValue();
											String locationName = map.get("location_name").toString();
								%>

								<OPTION value="<%=locationId%>"
									<%if (locationId == originalLocationId) {%> selected="selected"
									<%}%>><%=map.get("location_name")%></OPTION>
								<%
									}
								%>
						</SELECT></td>
					</tr>

					<tr>
						<td class="post-label"><b>Game Type:</b></td>
						<td><SELECT class="post-selection" name="game_type">
								<%
									int gameType = -1;
										if (request.getAttribute("game_type") != null) {
										  gameType = Integer.parseInt((String) request.getAttribute("game_type"));
										}
								%>
								<OPTION value="0" <%if (gameType == 0) {%> selected="selected"
									<%}%>>Step by step</OPTION>
								<OPTION value="1" <%if (gameType == 1) {%> selected="selected"
									<%}%>>All hints at once</OPTION>
						</SELECT></td>
					</tr>

					<tr>
						<td class="post-label"><b>Activation:</b></td>
						<td><SELECT class="post-selection" name="activation">
								<%
									int activation = -1;
										if (request.getAttribute("activation") != null) {
											Integer.parseInt((String) request
													.getAttribute("activation"));
										}
								%>
								<OPTION value="1" <%if (activation == 1) {%> selected="selected"
									<%}%>>Active</OPTION>
								<OPTION value="0" <%if (activation == 0) {%> selected="selected"
									<%}%>>Inactive</OPTION>
						</SELECT></td>
					</tr>

					<tr>
						<td />
						<td><input id="post-submit" type="submit" value="Submit" /></td>
					</tr>
				</table>
			</div>
		</div>
	</form>
</body>
<%
	} else {
		response.sendRedirect("index.jsp");
	}
%>
<%@ include file="footer.jsp"%>